
package poplar.dp.net;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.service.IoHandler;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.ssl.SslFilter;
import org.apache.mina.filter.logging.MdcInjectionFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import poplar.dp.net.SessionManager;

public class ProtocolHandler extends IoHandlerAdapter {	
	private final static Logger LOGGER = LoggerFactory.getLogger( ProtocolHandler.class );
		
	@Override
	public void sessionCreated( IoSession session ){		
		session.getConfig().setIdleTime( IdleStatus.BOTH_IDLE, 10 );
		
		System.out.println( "connect" );
	}
 
	@Override
	public void sessionClosed(IoSession session) throws Exception{
		LOGGER.info("CLOSED");
		
		System.out.println( "close" );
	}
	
	@Override
	public void sessionOpened(IoSession session) throws Exception{
		LOGGER.info("OPENED");
		String user = (String) session.getAttribute( "user" );		
	}
	
	@Override
	public void sessionIdle(IoSession session, IdleStatus status){
		LOGGER.info("*** IDLE #" + session.getIdleCount(IdleStatus.BOTH_IDLE) + " ***");
		
		System.out.println( "idle" );
	}
	
	@Override
	public void exceptionCaught(IoSession session, Throwable cause){
		session.close(true);
		
		System.out.println( "close" );
	}
	
	@Override
	public void messageReceived(IoSession session, Object message)
	throws Exception {
		LOGGER.info( "Received : " + message );
		//Write the received data back to remote peer
		session.write(((IoBuffer) message).duplicate());
		
		System.out.println( "recv" );
	}
	
	public ProtocolHandler(){		
	}
}

